<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS-Corner-03 Canvas</title>
</head>
<style>
    body{
        background:#ccc;
        text-align:center;
    }
    #c1{
        color:#fff;
    }
</style>
<body>
    本页面不需要启动服务器

    <h1>Pie 饼图</h1>
    <hr>
    <canvas id="c1" width="800" height="600"></canvas>

    <script>
        window.onload = function(){
            let oC = document.getElementById('c1')
            let gd = oC.getContext('2d')

            let cx = 400, cy=300, r=200
            let data = [
                { name: 'React', share: 45, color: '#C2B' },
                { name: 'Vue', share: 40, color: '#FA0' },
                { name: 'Angular', share: 15, color: '#BFF' },
            ]

            function pie(startAng, endAng, color){

                let x = cx+Math.cos(d2a(startAng))*r
                let y = cy+Math.sin(d2a(startAng))*r

                gd.beginPath()

                gd.moveTo(cx, cy)
                gd.lineTo(x, y)

                gd.arc(cx,cy,r,d2a(startAng), d2a(endAng), false)

                gd.closePath()

                gd.fillStyle = color
                gd.fill()
            }

            let sum = data.reduce((temp, item)=>{
                return temp + item.share
            }, 0)

            let currentAng = 180

            data.forEach((item)=>{
                let ang = 360/sum * item.share
                pie(currentAng, currentAng+ang, item.color)

                currentAng += ang
            })
        }

        function d2a(n){
            return n*Math.PI/180
        }
        function a2d(n){
            return n/180*Mathi.PI
        }
    </script>
</body>
</html>